package com.xiaoyg.proxy.cglib;


import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibDynamicProxy implements MethodInterceptor {

    // 维护目标对象
    private Object target;

    public CglibDynamicProxy(Object target) {
        this.target = target;
    }

    public Object newProxyInstance(){
        Enhancer en = new Enhancer();

        en.setSuperclass(target.getClass());
        en.setCallback(this);
        return en.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("CglibDynamicProxy，"+ method.getName()+"方法，执行之前");
        Object returnValue = method.invoke(target, args);
        System.out.println("CglibDynamicProxy，"+ method.getName()+"方法，执行之后");
        return returnValue;
    }
}
